<template>
  <a-modal
    v-model:open="visible"
    :mask-closable="false"
    width="85%"
    title="查看"
    :style="{ top: '20px' }"
    :footer="null"
  >
    <div v-if="visible" v-permission="['base-data:product:info:query']" v-loading="loading">
      <a-descriptions :column="3" :label-style="{ width: '120px' }" bordered>
        <a-descriptions-item label="编号" :span="1">{{ formData.code }}</a-descriptions-item>
        <a-descriptions-item label="名称" :span="1">{{ formData.name }}</a-descriptions-item>
        <a-descriptions-item label="简称" :span="1">{{ formData.shortName }}</a-descriptions-item>
        <a-descriptions-item label="SKU编号" :span="1">{{ formData.skuCode }}</a-descriptions-item>
        <a-descriptions-item label="简码" :span="1">{{
          formData.externalCode
        }}</a-descriptions-item>
        <a-descriptions-item label="分类" :span="1">{{
          formData.categoryName
        }}</a-descriptions-item>
        <a-descriptions-item label="品牌" :span="1">{{ formData.brandName }}</a-descriptions-item>
        <a-descriptions-item v-if="[1, 2].includes(formData.productType)" label="规格" :span="1">{{
          formData.spec
        }}</a-descriptions-item>
        <a-descriptions-item label="单位" :span="1">
          <unit-selector v-model:value="formData.unit" readOnly />
        </a-descriptions-item>
        <a-descriptions-item label="归属门店" :span="1">
          <span v-if="$utils.isEmpty(formData.shopId)">总部</span>
          <shop-selector v-else v-model:value="formData.shopId" readOnly />
        </a-descriptions-item>
        <a-descriptions-item
          v-if="[1].includes(formData.productType)"
          label="重量（kg）"
          :span="1"
          >{{
            $enums.PRODUCT_TYPE.NORMAL.equalsCode(formData.productType) ? formData.weight : '-'
          }}</a-descriptions-item
        >
        <a-descriptions-item
          v-if="[1].includes(formData.productType)"
          label="体积（cm³）"
          :span="1"
          >{{
            $enums.PRODUCT_TYPE.NORMAL.equalsCode(formData.productType) ? formData.volume : '-'
          }}</a-descriptions-item
        >
        <a-descriptions-item
          v-if="[1, 3].includes(formData.productType)"
          label="进项税率（%）"
          :span="1"
          >{{
            $enums.PRODUCT_TYPE.NORMAL.equalsCode(formData.productType) ? formData.taxRate : '-'
          }}</a-descriptions-item
        >
        <a-descriptions-item
          label="销项税率（%）"
          v-if="[1, 3].includes(formData.productType)"
          :span="1"
          >{{
            $enums.PRODUCT_TYPE.NORMAL.equalsCode(formData.productType) ? formData.saleTaxRate : '-'
          }}</a-descriptions-item
        >
        <a-descriptions-item
          v-if="[1].includes(formData.productType)"
          label="采购价（元）"
          :span="1"
          >{{
            $enums.PRODUCT_TYPE.NORMAL.equalsCode(formData.productType)
              ? formData.purchasePrice
              : '-'
          }}</a-descriptions-item
        >
        <a-descriptions-item
          v-if="[1, 2].includes(formData.productType)"
          label="销售价（元）"
          :span="1"
          >{{ formData.salePrice }}</a-descriptions-item
        >
        <a-descriptions-item
          v-if="[1, 2].includes(formData.productType)"
          label="零售价（元）"
          :span="1"
          >{{ formData.retailPrice }}</a-descriptions-item
        >
        <a-descriptions-item label="保质期（天）" :span="1">{{
          `${formData.expiryDay || '-'}天`
        }}</a-descriptions-item>
        <a-descriptions-item label="商品类型" :span="1">{{
          $enums.PRODUCT_TYPE.getDesc(formData.productType)
        }}</a-descriptions-item>
        <a-descriptions-item label="商品图片" :span="1">
          <div v-if="formData.imageUrl" class="detail-image-container">
            <a-image
              :src="formData.imageUrl"
              :alt="formData.name"
              :height="80"
              :width="150"
              class="detail-product-image"
              @click="previewImage(formData.imageUrl, formData.name)"
            />
          </div>
          <span v-else class="no-image">无图片</span>
        </a-descriptions-item>
        <a-descriptions-item label="状态" :span="1"
          ><available-tag :available="formData.available"
        /></a-descriptions-item>
        <a-descriptions-item label="商品介绍" :span="1">
          {{ formData.introduction }}
        </a-descriptions-item>
        <a-descriptions-item
          v-for="item in formData.properties"
          :key="item.id"
          :label="item.name"
          :span="1"
        >
          {{ item.textStr }}
        </a-descriptions-item>
      </a-descriptions>
      <vxe-grid
        v-if="[2].includes(formData.productType)"
        ref="grid"
        resizable
        show-overflow
        highlight-hover-row
        keep-source
        row-id="id"
        height="500"
        :data="productBundles"
        :columns="[
          {
            field: 'product',
            title: '单品',
            minWidth: 260,
            slots: { default: 'product_default' },
          },
          {
            field: 'spec',
            title: '规格',
            width: 140,
          },
          {
            field: 'bundle_num',
            title: '包含数量',
            width: 200,
            align: 'right',
            slots: { default: 'bundleNum_default' },
          },
          {
            field: 'salePrice',
            title: '销售价（元）',
            width: 200,
            align: 'right',
            slots: { default: 'salePrice_default' },
          },
          {
            field: 'retailPrice',
            title: '零售价（元）',
            width: 200,
            align: 'right',
            slots: { default: 'retailPrice_default' },
          },
        ]"
        :toolbar-config="{
          // 缩放
          zoom: false,
          // 自定义表头
          custom: false,
          // 右侧是否显示刷新按钮
          refresh: false,
          // 自定义左侧工具栏
          slots: {
            buttons: 'toolbar_buttons',
          },
        }"
      >
        <!-- 商品 列自定义内容 -->
        <template #product_default="{ row }">
          <product-selector
            v-model:value="row.productId"
            :request-params="{
              productType: [1, 4].join(','),
            }"
            @load-complete="
              (data) => {
                $nextTick(() => {
                  row.spec = data[0]?.spec;
                });
              }
            "
            read-only
          />
        </template>

        <!-- 包含数量 列自定义内容 -->
        <template #bundleNum_default="{ row }">
          {{ row.bundleNum }}
        </template>

        <!-- 销售价 列自定义内容 -->
        <template #salePrice_default="{ row }">
          {{ row.salePrice }}
        </template>

        <!-- 零售价 列自定义内容 -->
        <template #retailPrice_default="{ row }">
          {{ row.retailPrice }}
        </template>
      </vxe-grid>
      <vxe-grid
        v-if="[3].includes(formData.productType)"
        ref="specGrid"
        resizable
        show-overflow
        highlight-hover-row
        keep-source
        row-id="id"
        height="500"
        :data="formData.productData"
        :columns="tableColumn"
        :toolbar-config="{
          zoom: false,
          custom: false,
          refresh: false,
          slots: {
            buttons: 'toolbar_buttons',
          },
        }"
      >
        <!-- 规格属性值 列自定义内容 -->
        <template #propertyValue_default="{ columnIndex, row }">
          <span>
            {{
              modelorList
                .flatMap((p) => p.items)
                .find((item) => item.id === (row.property[columnIndex]?.propertyItemId || null))
                ?.name || ''
            }}
          </span>
        </template>
        <!-- 规格名称 列自定义内容 -->
        <template #spec_default="{ column, row }">
          {{ row[column.field] || '-' }}
        </template>
        <!-- sku编号 列自定义内容 -->
        <template #sku_default="{ column, row }">
          <span>
            {{ row[column.field] || '' }}
          </span>
        </template>
        <!-- 单位 列自定义内容 -->
        <template #unit_default="{ column, row }">
          <unit-selector v-model:value="row[column.field]" read-only />
        </template>
        <!-- 价格 列自定义内容 -->
        <template #price_default="{ column, row }">
          {{ row[column.field] || '-' }}
        </template>
        <!-- 数量 列自定义内容 -->
        <template #number_default="{ column, row }">
          {{ row[column.field] || '-' }}
        </template>
        <template #available_default="{ column, row }">
          <available-tag :available="row[column.field]" />
        </template>
      </vxe-grid>
    </div>
  </a-modal>
</template>
<script>
  import { defineComponent } from 'vue';
  import * as api from '@/api/base-data/product/info';
  import * as propertyApi from '@/api/base-data/product/property';
  import UnitSelector from '@/components/Selector/src/UnitSelector.vue';
  import ShopSelector from '@/components/Selector/src/ShopSelector.vue';

  export default defineComponent({
    // 使用组件
    components: { ShopSelector, UnitSelector },

    props: {
      id: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        // 是否可见
        visible: false,
        // 是否显示加载框
        loading: false,
        // 表单数据
        formData: {},
        modelorList: [],
        productBundles: [],
        // 多规格表格列
        tableColumn: [],
        // 多规格表格默认列
        defaultColumn: [
          {
            title: '规格',
            field: 'spec',
            minWidth: 140,
            slots: { default: 'spec_default' },
          },
          {
            title: 'sku编号',
            field: 'skuCode',
            minWidth: 140,
            slots: { default: 'sku_default' },
          },
          {
            title: '采购价（元）',
            field: 'purchasePrice',
            width: 120,
            type: 'price',
            slots: { default: 'price_default' },
          },
          {
            title: '零售价（元）',
            field: 'retailPrice',
            width: 120,
            type: 'price',
            slots: { default: 'price_default' },
          },
          {
            title: '销售价（元）',
            field: 'salePrice',
            width: 120,
            type: 'price',
            slots: { default: 'price_default' },
          },
          {
            title: '重量（kg）',
            field: 'weight',
            width: 120,
            type: 'number',
            slots: { default: 'number_default' },
          },
          {
            title: '体积',
            field: 'volume',
            width: 120,
            type: 'number',
            slots: { default: 'number_default' },
          },
          {
            title: '状态',
            field: 'available',
            width: 120,
            type: 'available',
            slots: { default: 'available_default' },
          },
        ],
      };
    },
    computed: {},
    created() {
      this.initFormData();
    },
    methods: {
      // 打开对话框 由父页面触发
      openDialog() {
        this.visible = true;

        this.$nextTick(() => this.open());
      },
      // 关闭对话框
      closeDialog() {
        this.visible = false;
        this.$emit('close');
      },
      // 初始化表单数据
      initFormData() {
        this.formData = {
          id: '',
          code: '',
          name: '',
          skuCode: '',
          externalCode: '',
          categoryName: '',
          brandName: '',
          spec: '',
          unit: '',
          stockUnit: '',
          salesUnit: '',
          retailUnit: '',
          expiryDay: null,
          purchasePrice: '',
          salePrice: '',
          retailPrice: '',
          available: '',
          introduction: '',
          properties: [],
        };
        this.productBundles = [];
        this.modelorList = [];
      },
      // 页面显示时触发
      open() {
        // 初始化数据
        this.initFormData();

        // 查询数据
        this.loadFormData();
      },
      // 查询数据
      loadFormData() {
        this.loading = true;
        api
          .get(this.id)
          .then((data) => {
            this.formData = data;
            this.selectCategory(this.formData.categoryId, this.formData);
            this.productBundles = data.productBundles;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      // 预览图片
      previewImage(imageUrl, title) {
        this.$preview.preview({
          current: imageUrl,
          urls: [imageUrl],
          title: title || '商品图片',
        });
      },
      selectCategory(val, formData) {
        this.modelorList = [];
        if (!this.$utils.isEmpty(val)) {
          propertyApi.getModelorByCategory(val).then((res) => {
            const modelorList = res;
            if (formData) {
              const properties = formData.properties || [];
              modelorList.forEach((item) => {
                item.text = (properties.filter((p) => p.id === item.id)[0] || {}).text;
                if (this.$enums.COLUMN_TYPE.MULTIPLE.equalsCode(item.columnType)) {
                  item.text = this.$utils.isEmpty(item.text) ? [] : item.text.split(',');
                }
              });
            }

            modelorList
              .filter((item) => this.$utils.isEmpty(item.text))
              .forEach((item) => {
                if (this.$enums.COLUMN_TYPE.MULTIPLE.equalsCode(item.columnType)) {
                  item.text = [];
                } else {
                  item.text = '';
                }
              });

            this.modelorList = modelorList;

            this.initPropertyColumn();
          });
        }
      },
      initPropertyColumn() {
        this.tableColumn = [];
        this.modelorList
          .filter((item) => [1, 2].includes(item.columnType))
          .map((item) => item.id)
          .forEach((item) => {
            this.tableColumn.push({
              title: this.modelorList.find((p) => p.id === item)?.name,
              field: `${item}`,
              minWidth: 120,
              fixed: 'left',
              slots: { default: 'propertyValue_default' },
            });
          });
        this.tableColumn.push(...this.defaultColumn);
      },
    },
  });
</script>
<style scoped>
  .detail-image-container {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .detail-product-image {
    width: 30px;
    height: 30px;
    object-fit: cover;
    border-radius: 4px;
    cursor: pointer;
    border: 1px solid #d9d9d9;
    transition: all 0.3s;
  }

  .detail-product-image:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .no-image {
    color: #999;
    font-size: 14px;
  }
</style>
